package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.CartMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.service.CartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description:
 * @author: nianqiang
 * @Version: V1.0
 */
@Service
public class CartServiceImpl implements CartService {

		@Autowired
		private CartMapper cartMapper;

		@Autowired
		private DishMapper dishMapper;

		@Autowired
		private SetmealMapper setmealMapper;


		/**
		 * 查询我的购物车
		 * @return
		 */
		@Override
		public List<ShoppingCart> list() {
				return cartMapper.findByQuery(
								ShoppingCart.builder()
												.userId(BaseContext.getCurrentId())
												.build());
		}

		/**
		 * 添加购物车
		 * @param shoppingCartDTO
		 */
		@Override
		public void add(ShoppingCartDTO shoppingCartDTO) {
				//1 参数校验
				Long userId = BaseContext.getCurrentId();
				if (userId == null) {
						throw new ShoppingCartBusinessException("用户未登录");
				}
				if (shoppingCartDTO.getDishId() == null && shoppingCartDTO.getSetmealId() == null) {
						throw new ShoppingCartBusinessException("必须选择菜品才可以加购物车");
				}

				//2 查询我的购物车 -- userId 查询 \ 菜品ID\口味 \ 套餐ID
				ShoppingCart shoppingCart = new ShoppingCart();
				BeanUtils.copyProperties(shoppingCartDTO, shoppingCart );
				//** 查询我的购物车 需要传递用户ID
				shoppingCart.setUserId(userId);
				List<ShoppingCart> cartList = cartMapper.findByQuery(shoppingCart);
				//3 购物车中有当前的菜品\套餐,则执行更新数据库 当前菜品\套餐的数量 +1
				if (cartList != null && cartList.size() > 0) {
						ShoppingCart cart = cartList.get(0);
						// 更新购物车菜品的数量
						cart.setNumber(cart.getNumber() + 1);
						//更新到数据库 update操作
						cartMapper.updateNumberById(cart);
				} else {
						//4 购物车中没有当前的菜品\套餐 执行添加购物车保存到数据库
						//4.1 判断当前用户选择的是 菜品还是套餐
						if (shoppingCartDTO.getDishId() != null) {
								// 查询菜品数据
								Dish dish = dishMapper.getById(shoppingCartDTO.getDishId());
								shoppingCart.setName(dish.getName());
								shoppingCart.setImage(dish.getImage());
								shoppingCart.setAmount(dish.getPrice());
						} else {
								// 查询套餐数据
								Setmeal setmeal = setmealMapper.getById(shoppingCartDTO.getSetmealId());
								shoppingCart.setName(setmeal.getName());
								shoppingCart.setImage(setmeal.getImage());
								shoppingCart.setAmount(setmeal.getPrice());
						}

						//更新菜品数量
						shoppingCart.setNumber(1);
						// 更新菜品时间
						shoppingCart.setCreateTime(LocalDateTime.now());
						// 保存到购物车数据库中
						cartMapper.insert(shoppingCart);

				}
		}
}
